#include "stream/osd_text.h"

namespace stream {

CVOsdText::CVOsdText(CVStreamOsdInfo* osd_info, LogInfo* log_info): 
  BaseOsd(osd_info, log_info) {

}

CVOsdText::~CVOsdText() {

}

int CVOsdText::init_params() {
  int ret = 0;
  std::string fontFile = "./simsun.ttc";

  if (!bf::exists(fontFile)){std::cout<<"no such file: "<<fontFile<<std::endl;return -1;}
  ft2 = cv::freetype::createFreeType2();
  if(ft2.empty()) {
    std::cout << "Failed to create FreeType2 object" << std::endl;
    spdlog::get("logger")->info("ERROR. CVOsdText::init_params: Failed to create FreeType2 object!\n");
    return -1;
   }
  ft2->loadFontData(fontFile,0);

  return 0;
}

int CVOsdText::draw_osd(stream::ImageBlob& buffer, std::vector<OSDDrawInfo>& osdd_ifos){
  CVStreamOsdInfo* osd_info = (CVStreamOsdInfo *)osd_ifo;

  cv::Scalar text_color;
  cv::Scalar box_color;
  if(ft2.empty()|| buffer.img.empty()) {
    std::cout << "no create FreeType2 object or img.empty!" << std::endl;
    spdlog::get("logger")->info("ERROR. CVOsdText::draw_osd: no create FreeType2 object or img.empty!\n");
    return -1;
  }
  for (auto& osdd_ifo : osdd_ifos) {
    //先画文字
    for (size_t idx = 0; idx < osdd_ifo.texts.size(); idx++) {
      text_color = osd_info->boxColorOK;
      box_color = osd_info->boxColorOK;
      // 通过首字母来判断绘制颜色 是报警信息还是正确信息
      if (osdd_ifo.texts[idx][0] == 'N') {
        text_color = osd_info->boxColorNG;
        box_color = osd_info->boxColorNG;
      }
      int x = osdd_ifo.x;
      int y = osdd_ifo.y - (int(idx)+1)*osd_info->fontHeight;
      cv::Point textOrg(x,y);
      std::string text = osdd_ifo.texts[idx].substr(1); //除了首字母之后的字

      ft2->putText(buffer.img,text,textOrg,osd_info->fontHeight,text_color,-1,4,true);

      // ft2->putText(frame,text,textOrg,fontHeight,cv::Scalar(0, 0, 255),-1,4,true);
    }

    //画框
    if (osdd_ifo.w > 0 && osdd_ifo.h > 0) {
      cv::Rect rect_box(osdd_ifo.x,osdd_ifo.y, osdd_ifo.w, osdd_ifo.h);
      cv::rectangle(buffer.img,rect_box,box_color,osd_info->boxThick);
    }

  }

  return 0;
}

}